package com.java.demo.thread;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @auther zhangwj
 * @date 2020/9/16 3:28 下午
 */
public class ReadWriteDemo {

    private static int count = 0;

    public static void main(String[] args) {
        ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock();
        Lock readLock = readWriteLock.readLock();
        Lock writeLock = readWriteLock.writeLock();
        for (int i = 0; i < 100; i++) {
            new Thread(() -> {
                ReadWriteDemo.write(writeLock);
            }).start();
            new Thread(() -> {
                ReadWriteDemo.read(readLock);
            }).start();
            new Thread(() -> {
                ReadWriteDemo.read(readLock);
            }).start();
        }
    }

    public static void read(Lock lock) {
        try {
            lock.lock();
            Thread.sleep(200);
            System.out.println("读数据" + count);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public static void write(Lock lock) {
        try {
            lock.lock();
            Thread.sleep(200);
            count++;
            System.out.println("写数据");
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }

    }
}
